package com.winit.openapi.chinapost.controller;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.winit.common.spi.context.CommandContext;
import com.winit.oms.spi.OrderException;
import com.winit.oms.spi.isp.ChinaPostBigPackageService;
import com.winit.oms.spi.isp.ISPOrderLineService;
import com.winit.oms.spi.isp.ISPOrderService;
import com.winit.oms.spi.isp.command.bigPackage.SaveCPBigPackageCommand;
import com.winit.oms.spi.isp.vo.CPBagsElementsVO;
import com.winit.openapi.chinapost.constants.ChinaPostErrorCode;
import com.winit.openapi.chinapost.model.BagsElement;
import com.winit.openapi.chinapost.model.BagsList;
import com.winit.openapi.chinapost.model.RequestObject;
import com.winit.openapi.chinapost.model.ResponsesObject;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.vms.spi.TrackService;

/**
 * 
 * 中邮总包接口Controller
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * jianhua.huang 	1.0  		2015-7-21 	Created
 * 
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "/CPBigPackage")
public class ChinaPostBigPackageController extends BaseController {

	private static final Logger logger = LoggerFactory
			.getLogger(ChinaPostBigPackageController.class);

	@Resource
	private ChinaPostBigPackageService chinaPostBigPackageService;

	@Resource
	private TrackService trackService;

	@Resource
	private ISPOrderService iSPOrderService;

	@Resource
	private ISPOrderLineService orderLineService;

	static JAXBContext jaxbContext;
	static Unmarshaller unmarshaller;

	static {
		try {
			// 返回报文，解析
			jaxbContext = JAXBContext.newInstance(BagsList.class);
			unmarshaller = jaxbContext.createUnmarshaller();
		} catch (Exception e) {
			e.printStackTrace();
			throw new ApiException(ChinaPostErrorCode.ERROR_S01);
		}
	}

	@RequestMapping(value = "/API")
	@ResponseBody
	public ResponsesObject doAPI(@ModelAttribute RequestObject requestObject) {
		logger.info("BigPackage中邮请求参数-----------》" + JSON.toJSONString(requestObject));
		String errorCode = null;
		String txLogisticID=null;
		try {
			// step 1 校验参数
			verifyParameters(requestObject);
			// setp 2 验证签名
		    verifySignature(requestObject);

			List<BagsElement> bagsElement = null;
			synchronized (unmarshaller) {
				BagsList bagsList = (BagsList) unmarshaller
						.unmarshal(new StringReader(requestObject
								.getLogistics_interface()));
				bagsElement = bagsList.getBagsElement();
			}
			// 设置上下文
			CommandContext ctx = CommandContext.getContext();
			// 构建数据
			List<CPBagsElementsVO> list=builBigPackageData(bagsElement);
			SaveCPBigPackageCommand command=new SaveCPBigPackageCommand();
			command.setCtx(ctx);
			command.setBagsElementsVO(list);
			//保存大包数据
			Map<String, String> map=chinaPostBigPackageService.saveCPBigPackage(command);
			for(Map.Entry<String, String> entry:map.entrySet()){
				txLogisticID=entry.getValue(); //总包号
				errorCode=entry.getKey();//错误码
			}
		} catch (JAXBException e) {
			errorCode = ChinaPostErrorCode.ERROR_S01;
			logger.warn("illegal json string:" + e);
		} catch (ApiException e) {
			errorCode = e.getErrorCode();
			logger.warn("illegal json string:" + e);
		}catch(OrderException e){
			errorCode = e.getErrorCode();
			logger.warn("illegal json string:" + e);
		}catch (Exception e) {
			errorCode = ChinaPostErrorCode.ERROR_B98;
			logger.warn("illegal json string:" + e);
		}
		ResponsesObject responsesObject = this.getResponsesObject(errorCode);
		logger.info("BigPackage中邮请求返回参数-----------》" + JSON.toJSONString(responsesObject)
				+ "errorCode: =" + errorCode);
		return responsesObject;
	}

	private List<CPBagsElementsVO> builBigPackageData(List<BagsElement> listElements){
		if (listElements == null) {
			throw new ApiException(ChinaPostErrorCode.ERROR_B03);
		}
		List<CPBagsElementsVO> cpBagsElements=new ArrayList<CPBagsElementsVO>();
		CPBagsElementsVO bagsElementsVO=null;
		List<String> listMailNo=null;
		//构建VO数据
		for(BagsElement element:listElements){
			bagsElementsVO=new CPBagsElementsVO();
			listMailNo=new ArrayList<String>();
			bagsElementsVO.setBagNos(element.getBagNos());
			bagsElementsVO.setLogisticProviderID(element.getLogisticProviderID());
			bagsElementsVO.setTime(element.getTime());
			bagsElementsVO.setFacilityNo(element.getFacilityNo());
			bagsElementsVO.setFacilityName(element.getFacilityName());
			bagsElementsVO.setCountry(element.getCountry());
			for (int i = 0; i < element.getMailsElement().size(); i++) {
				listMailNo.add(element.getMailsElement().get(i).getMailNos());
			}
			bagsElementsVO.setMailNo(listMailNo);
			cpBagsElements.add(bagsElementsVO);
		}
		return cpBagsElements;
	}
}
